<?php
namespace Seller\Controller;
use Seller\Logic\GoodsLogic;
use Think\AjaxPage;
use Think\Page;

class GoodsTianxinController extends BaseController {
    /**
     * 商品类型  用于设置商品的属性
     */
    public function goodsTypeList(){
		$store_id=$_SESSION['store_id'];
        $model = M("GoodsType");                
        $count = $model->where("store_id='$store_id'")->count();        
        $Page  = new Page($count,10);
        $show  = $Page->show();
        $goodsTypeList = $model->where("store_id='$store_id'")->order("id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('show',$show);
        $this->assign('goodsTypeList',$goodsTypeList);
        $this->display('goodsTypeList');
    }
    
    
    /**
     * 添加修改编辑  商品属性类型
     */
    public  function addEditGoodsType(){
            $id = $_GET['id'] ? $_GET['id'] : 0;
            $model = M("GoodsType"); 
			$store_id=$_SESSION['store_id'];
			$_POST['store_id']=$store_id;
            if(IS_POST)
            {
                  $id = $_POST['id'];
                    $a = $model->create();
                    // 编辑操作
                    if($id){
                        unset($_POST['id']);
                        $res=$model->where(array('id'=>$id))->save($_POST);
                        if ($res){
                            $return_arr = array(
                                'status' => 1,
                                'msg'   => '修改成功',
                            );
                            exit(json_encode($return_arr));
                        }else{
                            $return_arr = array(
                                'status' => 0,
                                'msg'   => '修改失败',
                            );
                            exit(json_encode($return_arr));
                        }
                    }                        
                    else // 添加操作
                    {
                        unset($_POST['id']);

                        $res = $model->add($_POST);
                        if ($res){
                            $return_arr = array(
                                'status' => 1,
                                'msg'   => '添加成功',
                            );
                            exit(json_encode($return_arr));
                        }else{
                            $return_arr = array(
                                'status' => 0,
                                'msg'   => '添加失败',
                            );
                            exit(json_encode($return_arr));

                        }

                    }
                    
//                    // 类型规格对应关系表
//                    if($id && !empty($_POST['spec_id']))
//                    {
//                        $dataList = array();
//                        foreach($_POST['spec_id'] as $k => $v)
//                          $dataList[] = array('type_id'=>$id,'spec_id'=>$v);
//
//                        M('spec_type')->where("type_id = $id")->delete(); // 先把类型规格 表对应的 删除掉 然后再重新添加
//                        M('spec_type')->addAll($dataList);
//                    }
//
//					if(empty($_POST['spec_id'])){
//						 M('spec_type')->where("type_id = $id")->delete(); // 先把类型规格 表对应的 删除掉 然后再重新添加
//					}
//
//                    // 处理商品属性
//                    if($id && !empty($_POST['attr_name']))
//                    {
//                        $dataList = array();
//                        foreach($_POST['attr_name'] as $k => $v)
//                        {
//                            $_POST['attr_values'][$k] = str_replace('_', '', $_POST['attr_values'][$k]); // 替换特殊字符
//                            $_POST['attr_values'][$k] = str_replace('@', '', $_POST['attr_values'][$k]); // 替换特殊字符
//                            $_POST['attr_values'][$k] = trim($_POST['attr_values'][$k]);
//                            $_POST['attr_index'][$k] = $_POST['attr_index'][$k] ? $_POST['attr_index'][$k] : 0; // 是否显示
//                           $attribute  = array(
//                                'attr_name'=>$v,
//                                'type_id'=>$id,
//                                'attr_index'=>$_POST['attr_index'][$k],
//                                'attr_values'=>$_POST['attr_values'][$k],
//                                'attr_input_type'=>'1',
//                                'order'=>$_POST['order'][$k],
//                                );
//                            if(empty($_POST['attr_id'][$k]))
//                                $dataList[] = $attribute;
//                            else{
//                                $attribute['attr_id'] = $_POST['attr_id'][$k];
//                                M('goods_attribute')->save($attribute);
//                            }
//                        }
//                        // 插入属性
//                       if($dataList)
//                           M('goods_attribute')->addAll($dataList);
//                    }
                
//                    $this->success("操作成功!!!",U('Seller/GoodsTianxin/goodsTypeList'));
//                    exit;
            }           
           $goodsType = $model->where("id = $id")->find();   
           $GoodsLogic = new GoodsLogic(); 		   
		   $cat_list = M('store_goods_class')->where("parent_id = 0  AND  store_id='$store_id'")->select(); // 已经改成联动菜单     
           $attributeList = M('goods_attribute')->where("type_id = $id")->select();
           $this->assign('attributeList',$attributeList);
           $this->assign('cat_list',$cat_list);
//           $this->assign('level_cat',$level_cat);
           $this->assign('goodsType',$goodsType);
           $this->display('_goodsType');           
    }
     
    
    /**
     * 更改指定表的指定字段
     */
    public function updateField(){
        $primary = array(
                'goods' => 'goods_id',
                'goods_category' => 'id',
                'brand' => 'id',            
                'goods_attribute' => 'attr_id',
        		'ad' =>'ad_id',            
        );        
        $model = D($_POST['table']);
        $model->$primary[$_POST['table']] = $_POST['id'];
        $model->$_POST['field'] = $_POST['value'];        
        $model->save();   
        $return_arr = array(
            'status' => 1,
            'msg'   => '操作成功',                        
            'data'  => array('url'=>U('Seller/GoodsTianxin/goodsAttributeList')),
        );
        $this->ajaxReturn(json_encode($return_arr));
    }
    /**
     * 动态获取商品属性输入框 根据不同的数据返回不同的输入框类型
     */
    public function ajaxGetAttrInput(){
        $GoodsLogic = new GoodsLogic();
        $str = $GoodsLogic->getAttrInput($_REQUEST['goods_id'],$_REQUEST['type_id']);
        exit($str);
    }
        
    
    /**
     * 删除商品类型 
     */
    public function delGoodsType()
    {
        // 判断 商品规格        `tp_spec_type`   `tp_brand_type` 
        $count = M("spec")->where("goods_type_id = {$_GET['id']}")->count();
        $count > 0 && $this->error('该类型下有商品规格不能删除!',U('Seller/GoodsTianxin/goodsTypeList'));
        
        $count = M("brand_type")->where("type_id = {$_GET['id']}")->count();
        $count > 0 && $this->error('该类型下有管理品牌不能删除!',U('Seller/GoodsTianxin/goodsTypeList'));
        
        // 判断 商品属性
        $count = M("GoodsAttribute")->where("type_id = {$_GET['id']}")->count();
        $count > 0 && $this->error('该类型下有商品属性不能删除!',U('Seller/GoodsTianxin/goodsTypeList'));
        // 删除分类
        M('GoodsType')->where("id = {$_GET['id']}")->delete();   
        $this->success("操作成功!!!",U('Seller/GoodsTianxin/goodsTypeList'));
    }

    /**
     * 删除商品属性
     */
    public function delGoodsAttribute()
    {
        $id = I('id');
        if(empty($id))  return;
        // 删除 属性
        M("GoodsAttr")->where("attr_id = $id")->delete();
        M('GoodsAttribute')->where("attr_id = $id")->delete();
    }            
    
    /**
     * 删除商品规格
     */
    public function delGoodsSpec()
    {
        // 判断 商品规格项
        $count = M("SpecItem")->where("spec_id = {$_GET['id']}")->count("1");
        $count > 0 && $this->error('此规格有规格值不得删除!',U('Seller/GoodsTianxin/specList',array('goods_type_id'=>$_GET['goods_type_id'])));
        // 删除分类

        M('Spec')->where("id = {$_GET['id']}")->delete();
        M('spec_type')->where("type_id = {$_GET['goods_type_id']} and spec_id = {$_GET['id']}")->delete();
        $this->success("操作成功!!!",U('Seller/GoodsTianxin/specList',array('goods_type_id'=>$_GET['goods_type_id'])));
    } 
    /**
     * ajax 获取 品牌列表
     */
    public function getBrandByCat(){
        $db_prefix = C('DB_PREFIX');
        $cat_id = I('cat_id');
        $level = I('l');
        $type_id = I('type_id');        
        
        if($type_id)
            $list = M('brand')->join("left join {$db_prefix}brand_type on {$db_prefix}brand.id = {$db_prefix}brand_type.brand_id and  type_id = $type_id")->order('id')->select();    
        else    
            $list = M('brand')->order('id')->select();        
        
        $goods_category_list = M('goods_category')->where("id in(select cat_id1 from {$db_prefix}brand) ")->getField("id,name,parent_id");
        $goods_category_list[0] = array('id'=>0, 'name'=>'默认');
        asort($goods_category_list);
        $this->assign('goods_category_list',$goods_category_list);        
        $this->assign('type_id',$type_id);
        $this->assign('list',$list);
        $this->display();
    }
    
    
    /**
     * ajax 获取 规格列表
     */
    public function getSpecByCat(){
        
        $db_prefix = C('DB_PREFIX');
        $cat_id = I('cat_id');
        $level = I('l');
        $type_id = I('type_id');
		$store_id=$_SESSION['store_id'];
        if($type_id)            
            $list = M('spec')->where("store_id='$store_id'")->join("left join {$db_prefix}spec_type on {$db_prefix}spec.id = {$db_prefix}spec_type.spec_id  and  type_id = $type_id")->order('id')->select();
        else    
            $list = M('spec')->where("store_id='$store_id'")->order('id')->select();        
                       
        $goods_category_list = M('store_goods_class')->where("cat_id in(select store_cat_id1 from {$db_prefix}spec) ")->getField("cat_id,cat_name,parent_id");
        $goods_category_list[0] = array('id'=>0, 'name'=>'默认');
        asort($goods_category_list);               
        $this->assign('goods_category_list',$goods_category_list);
        $this->assign('type_id',$type_id);
        $this->assign('list',$list);
        $this->display();
    }    
    
    
    
    /**
     * 商品规格列表    
     */
    public function specList(){

		$store_id=$_SESSION['store_id'];
        $id=I('goods_type_id','');

		if($store_id){
			$where = 'parent_id = 0 AND store_id='.$store_id;
		}
        $cat_list = M('store_goods_class')->where($where)->getField('cat_id,cat_name,parent_id'); // 已经改成联动菜单

        $name = M('goods_type')->where("id='$id'")->getField('name'); // 获取所属类型名称
        $this->assign('cat_list',$cat_list);
        $this->assign('goods_type_id',$id);
        $this->assign('name',$name);
        $this->display();
    }
    
    
    /**
     *  商品规格列表
     */
    public function ajaxSpecList(){ 
        //ob_start('ob_gzhandler'); // 页面压缩输出
        $where = ' 1 = 1 '; // 搜索条件 
		$store_id=$_SESSION['store_id'];
        $goods_type_id=$_GET['goods_type_id'];

        if($store_id){
			$where .= 'AND store_id='.$store_id.' and goods_type_id = '.$goods_type_id;
		}

        I('cat_id1')   && $where = "$where and store_cat_id1 = ".I('cat_id1') ;
        // 关键词搜索               
        $model = D('spec');
        $count = $model->where($where)->count();
        $Page       = new AjaxPage($count,13);
        $show = $Page->show();
        
//        $cat_list = M('store_goods_class')->where("parent_id = 0")->getField('cat_id,cat_name'); // 已经改成联动菜单
        $specList = $model->where($where)->order('`store_cat_id1` desc')->limit($Page->firstRow.','.$Page->listRows)->select();
//        $this->assign('cat_list',$cat_list);
        $this->assign('specList',$specList);
        $this->assign('page',$show);// 赋值分页输出                        
        $this->assign('goods_type_id',$goods_type_id);
        $this->display();
    }      
    /**
     * 添加修改编辑  商品规格
     */
    public  function addEditSpec(){
                        
            $model = D("spec");  
			$store_id=$_SESSION['store_id'];
			$goods_type_id=$_GET['goods_type_id'];

			if($store_id){
				$where = 'AND store_id='.$store_id;
			}			
            $type = $_POST['id'] > 0 ? 1: 0; // 标识自动验证时的 场景 1 表示插入 2 表示更新

			$_POST['store_id']=$store_id;
            if(($_GET['is_ajax'] == 1) && IS_POST)//ajax提交验证
            {
                C('TOKEN_ON',false);
                $goods_type_id = $_POST['goods_type_id'];
                $name = $_POST['name'];
                $store_id=$_SESSION['store_id'];

                if(!$model->create(NULL,$type))// 根据表单提交的POST数据创建数据对象                 
                {
                    //  编辑
                    $return_arr = array(
                        'status' => -1,
                        'msg'   => '操作失败',
                        'data'  => $model->getError(),
                    );
                    $this->ajaxReturn(json_encode($return_arr));
                }else {
                   // C('TOKEN_ON',true); //  form表单提交

                    //查看该类型下的规格是否存在
					// if($goods_type_id&&$name&&$store_id){
						
					// 	$spec = $model->where("goods_type_id = $goods_type_id and name = '$name' and store_id = '$store_id'")->find();
					// 	if($spec){
					// 		$return_arr = array(
					// 			'status' => 1,
					// 			'msg'   => '该类型下已存在该规格',
					// 			'data'  => array('url'=>U('Admin/Goods/specList',array('goods_type_id'=>$_POST['goods_type_id']))),
					// 		);
					// 		$this->ajaxReturn(json_encode($return_arr));
					// 		exit;
					// 	}
					// }
                    if ($type)
                    {
                        $model->save(); // 写入数据到数据库                        
                    }
                    else
                    {
                        $insert_id = $model->add(); // 写入数据到数据库
                        //商品类型和规格对应表
                        if($insert_id && !empty($_POST['goods_type_id']))
                        {
                            $dataList = array('type_id'=>$_POST['goods_type_id'],'spec_id'=>$insert_id);
                            M('spec_type')->add($dataList);
                        }
                    }


                    $return_arr = array(
                        'status' => 1,
                        'msg'   => '操作成功',
                        'data'  => array('url'=>U('Seller/GoodsTianxin/specList',array('goods_type_id'=>$_POST['goods_type_id']))),
                    );
                    $this->ajaxReturn(json_encode($return_arr));
                }  
            }                
           // 点击过来编辑时                 
           $id = $_GET['id'] ? $_GET['id'] : 0;       
           $spec = $model->where("id = $id")->find();

           $cat_list = M('store_goods_class')->where("parent_id = 0  AND  	store_id='$store_id'")->getField('cat_id,cat_name,parent_id'); // 已经改成联动菜单
           $this->assign('cat_list',$cat_list);

           $this->assign('spec',$spec);                                 
           $this->assign('goods_type_id',$goods_type_id);
           $this->display('_spec');
    }  
    
    
    /**
     * 动态获取商品规格选择框 根据不同的数据返回不同的选择框
     */
    public function ajaxGetSpecSelect(){
        $goods_id = $_GET['goods_id'] ? $_GET['goods_id'] : 0;        
        $GoodsLogic = new GoodsLogic();
        //$_GET['spec_type'] =  13;
        $specList = D('Spec')->where("type_id = ".$_GET['spec_type'])->order('`order` desc')->select();
        foreach($specList as $k => $v)        
            $specList[$k]['spec_item'] = D('SpecItem')->where("spec_id = ".$v['id'])->getField('id,item'); // 获取规格项                
        
        $items_id = M('SpecGoodsPrice')->where('goods_id = '.$goods_id)->getField("GROUP_CONCAT(`key` SEPARATOR '_') AS items_id");
        $items_ids = explode('_', $items_id);       
        
        // 获取商品规格图片                
        if($goods_id)
        {
           $specImageList = M('SpecImage')->where("goods_id = $goods_id")->getField('spec_image_id,src');                 
        }        
        $this->assign('specImageList',$specImageList);
        
        $this->assign('items_ids',$items_ids);
        $this->assign('specList',$specList);
        $this->display('ajax_spec_select');        
    }    
    
    /**
     * 动态获取商品规格输入框 根据不同的数据返回不同的输入框
     */    
    public function ajaxGetSpecInput(){     
         $GoodsLogic = new GoodsLogic();
         $goods_id = $_REQUEST['goods_id'] ? $_REQUEST['goods_id'] : 0;
         $str = $GoodsLogic->getSpecInput($goods_id ,$_POST['spec_arr']);
         exit($str);   
    }

}